package com.atguigu.juc.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @Description: AtomicIntegerFieldUpdater 局部加锁
 * @author： yeswater
 * @create： 2024/5/30
 */

public class AtomicIntegerFieldUpdaterDemo {
	
	private static class BankAccount{
		
		String bankName = "CCB";
		public volatile int money = 0;
		
		public void add(){
			money++;
		}
		
		AtomicIntegerFieldUpdater<BankAccount> fieldUpdater = AtomicIntegerFieldUpdater.newUpdater(BankAccount.class, "money");
		
		public void transMoney(BankAccount bankAccount){
			fieldUpdater.getAndIncrement(bankAccount);
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		BankAccount bankAccount = new BankAccount();
		CountDownLatch countDownLatch = new CountDownLatch(10);
		for (int i = 0; i < 10; i++) {
			new Thread(() -> {
				try {
					for (int i1 = 0; i1 < 1000; i1++) {
						bankAccount.transMoney(bankAccount);
					}
				} finally {
					countDownLatch.countDown();
				}
			}, "Thread-" + i).start();
		}
		countDownLatch.await();
		System.out.println("result:" + bankAccount.money);
	}
	
}
